package mysql

import (
	"database/sql"
	"gitee.com/captials-team/ubdframe/src/common"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	mysql2 "github.com/go-sql-driver/mysql"
	"net"
	"time"
)

func NewConn(c configstc.DBConfig, fs ...func(config *mysql2.Config)) (*sql.DB, error) {
	newDb, err := sql.Open("mysql", FormatDSN(c, fs...))
	if err != nil {
		return nil, err
	}

	//默认
	if c.MaxIdleConn <= 0 {
		c.MaxIdleConn = MaxIdleConn
	}
	if c.MaxOpenConn <= 0 {
		c.MaxOpenConn = MaxOpenConn
	}
	if c.MaxLifeTime <= 0 {
		c.MaxLifeTime = int(MaxLifeTime / time.Second)
	}
	if c.MaxIdleTime <= 0 {
		c.MaxIdleTime = int(MaxIdleTime / time.Second)
	}
	newDb.SetMaxIdleConns(c.MaxIdleConn)
	newDb.SetMaxOpenConns(c.MaxOpenConn)
	newDb.SetConnMaxLifetime(time.Duration(c.MaxLifeTime) * time.Second)
	newDb.SetConnMaxIdleTime(time.Duration(c.MaxIdleTime) * time.Second)

	return newDb, nil
}

// FormatDSN 格式化为dsn
func FormatDSN(c configstc.DBConfig, fs ...func(config *mysql2.Config)) string {
	if c.DbDsn != "" {
		return c.DbDsn
	}
	dbConfig := mysql2.NewConfig()
	dbConfig.User = c.DbUser
	dbConfig.Passwd = c.DbPassword
	dbConfig.Net = "tcp"
	dbConfig.Addr = net.JoinHostPort(c.DbHost, c.DbPort)
	dbConfig.DBName = c.DbName
	dbConfig.MultiStatements = true
	dbConfig.RejectReadOnly = false
	dbConfig.ParseTime = true
	dbConfig.Loc = time.Local //默认用本地时区
	dbConfig.Params = make(map[string]string)
	if c.MaxConcatLen != "" {
		dbConfig.Params["group_concat_max_len"] = c.MaxConcatLen
	}
	if c.TimeZone != "" {
		var err error
		dbConfig.Loc, err = time.LoadLocation(c.TimeZone)
		common.ErrPanic(err)
	}

	if len(fs) > 0 {
		for _, f := range fs {
			f(dbConfig)
		}
	}

	return dbConfig.FormatDSN()
}
